from flask_cors import CORS
from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
import re
import hashlib
import jwt
from datetime import datetime
from functools import wraps





app = Flask(__name__)
CORS(app, resources={r"/*": {"origins": "*"}})



app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:password@192.168.167.24/liutest'  # 替换为您的数据库连接信息
db = SQLAlchemy(app)


serctKey ="1234567890123456abcdefg"
def hash_password(password: str) -> str:
    return hashlib.sha256(password.encode()).hexdigest()
from flask import request, jsonify
import jwt
from functools import wraps


def token_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        token = request.headers.get('x-token')

        if not token:
            return jsonify({'message': 'Token is missing'}), 401

        try:
            payload = jwt.decode(token, serctKey, algorithms=['HS256'])
        except jwt.ExpiredSignatureError:
            return jsonify({'message': 'Token has expired'}), 401
        except jwt.InvalidTokenError:
            return jsonify({'message': 'Invalid token'}), 401

        # 排除 login 和 register 请求
        if request.path == '/login' or request.path == '/register':
            return f(*args, **kwargs)

        return f(*args, **kwargs)

    return decorated_function


class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(50), unique=True, nullable=False)
    password = db.Column(db.String(50), nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)

@app.route('/register', methods=['POST'])
def register():
    data = request.get_json()
    username = data.get('username')
    password = data.get('password')
    email = data.get('email')
    message = ''
    isReg = True

    # Check if user already exists
    user = User.query.filter_by(username=username).first()
    if user:
        response_data = {
            "code": "0000",
            "data": {
                "isReg": False,
            },
            "msg": "该用户已经存在"
        }
        return jsonify(response_data), 200
    # Validate email format
    if not re.match(r"[^@]+@[^@]+\.[^@]+", email):
        response_data = {
            "code": "0000",
            "data": {
                "isReg": False,
            },
            "msg": "无效的邮件格式"
        }
        return jsonify(response_data), 200

    # Generate and send verification email
    # Code for sending email goes here
    hashed_password = hash_password(password)

    # Create new user
    new_user = User(username=username, password=hashed_password, email=email)
    db.session.add(new_user)
    db.session.commit()
    response_data = {
        "code": "0000",
        "data": {
            "isReg": isReg,
        },
        "msg": "注册成功"
    }
    return jsonify(response_data), 200


@app.route('/login', methods=['POST'])
def login():
    data = request.get_json()
    username = data.get('username')
    password = data.get('password')
    hashed_password = hash_password(password)
    user = User.query.filter_by(username=username).first()
    if user and user.password == hashed_password:
        payload = {'username': username}
        token = jwt.encode(payload, serctKey, algorithm='HS256')
        response_data = {
            "code": "0000",
            "data": {
                "username": username,
                "token": token,
                "id": user.id,
                "eamil": user.email
            },
            "msg": "登录成功"
        }
        return jsonify(response_data), 200



class Task(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    taskname = db.Column(db.String(32), nullable=False)
    taskdesc = db.Column(db.Text, default='')
    status = db.Column(db.String(20), default='1')
    user_id = db.Column(db.Integer, nullable=True)
    endtime = db.Column(db.DateTime, nullable=True)


@app.route('/mod_task', methods=['POST'])
@token_required
def mod_task():
    data = request.get_json()
    id = data.get('id')
    taskdesc = data.get('taskdesc')
    taskname = data.get('taskname')
    status = data.get('status')
    endtime = data.get('endtime')
    task = Task.query.get(id)
    if not task:
        return jsonify({"msg": "未找到任务"}), 404
    if taskdesc:
        task.taskdesc = taskdesc
    if taskname:
        task.taskname = taskname
    if status:
        task.status = status
    if endtime:
        task.endtime = endtime
    db.session.commit()
    response_data = {
        "code": "0000",
        "data": True,
        "msg": "ok"
    }
    return jsonify(response_data), 200


@app.route('/update_task', methods=['POST'])
@token_required
def update_task():
    data = request.get_json()
    id = data.get('id')
    taskdesc = data.get('taskdesc')
    taskname = data.get('taskname')
    status = data.get('status')
    endtime = data.get('endtime')
    task = Task.query.get(id)
    if not task:
        return jsonify({"msg": "未找到任务"}), 404
    if taskdesc:
        task.taskdesc = taskdesc
    if taskname:
        task.taskname = taskname
    if status:
        task.status = status
    if endtime:
        task.endtime = endtime
    db.session.commit()
    response_data = {
        "code": "0000",
        "data": True,
        "msg": "ok"
    }
    return jsonify(response_data), 200



@app.route('/create_task', methods=['POST'])
@token_required
def create_task():
    token = request.headers.get('x-token')
    decoded_token = jwt.decode(token, serctKey, algorithms=['HS256'])
    username = decoded_token.get('username')
    user = User.query.filter_by(username=username).first()
    data = request.get_json()
    new_task = Task(
        taskname=data.get('taskname'),
        taskdesc=data.get('taskdesc', ''),
        status=data.get('status'),
        user_id=user.id,
        endtime=data.get('endtime')
    )
    db.session.add(new_task)
    db.session.commit()
    response_data = {
        "code": "0000",
        "data": True,
        "msg": "ok"
    }
    return jsonify(response_data), 200

#查看任务列表
@app.route('/tasks', methods=['GET'])
@token_required
def get_tasks():
    token = request.headers.get('x-token')
    decoded_token = jwt.decode(token, serctKey, algorithms=['HS256'])
    username = decoded_token.get('username')
    user = User.query.filter_by(username=username).first()
    if user:
        tasks = Task.query.filter_by(user_id=user.id).all()
        task_list = []

        for task in tasks:
            task_data = {
                'id': task.id,
                'taskname': task.taskname,
                'taskdesc': task.taskdesc,
                'status': task.status,
                'user_id': task.user_id,
                'endtime': task.endtime
            }
            task_list.append(task_data)

        response_data = {
            "code": "0000",
            "data": task_list,
            "msg": "ok"
        }
    else:
        response_data = {
            "code": "0000",
            "data": [],
            "msg": "ok"
        }

    return jsonify(response_data), 200



@app.route('/menus', methods=['GET'])
@token_required
def get_menus():
        response_data = {
            "code": "0000",
            "data": [],
            "msg": "ok"
        }
        return jsonify(response_data), 200

@app.route('/tasks/<int:id>', methods=['DELETE'])
@token_required
def delete_task(id):
    token = request.headers.get('x-token')
    task = Task.query.get(id)
    if task:
        db.session.delete(task)
        db.session.commit()
        response_data = {
            "code": "0000",
            "data": True,
            "msg": "ok"
        }
    return jsonify(response_data), 200






if __name__ == '__main__':
    app.run(port=8123)
